package com.meta.platform.login.plus.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 验证码工具类
 *
 * @author pengjianfeng
 * @version 1.0
 * @date 2021/1/12 9:58 上午
 */
@Slf4j
public final class VCodeUtils {
    
    private static final int MIN_LENGTH = 4;
    
    private static final int MAX_LENGTH = 8;
    
    /**
     * 生成指定位数的验证码
     * 
     * @param length 验证码长度，最小4位
     * @return
     */
    public static String getVCode(int length) {
        length = length < 4 ? MIN_LENGTH : (length > 8 ? MAX_LENGTH : length);
        
        StringJoiner joiner = new StringJoiner("");
        for (int i = 0; i < length; i++) {
            joiner.add(String.valueOf(RandomUtils.nextInt(1, 10)));
        }
        
        return joiner.toString();
    }
    
    /**
     * 验证手机号码
     *
     * @param mobile
     * @return
     */
    public static boolean isPhoneNumber(String mobile) {
        try {
            Pattern pattern = Pattern.compile("1\\d{10}$");
            Matcher matcher = pattern.matcher(mobile);
            return matcher.matches();
        }
        catch (Exception e) {
            log.error("手机号码验证异常，mobiles={}", mobile, e);
        }
        return false;
    }
    
    /**
     * 验证密码
     *
     * @param password 密码
     * @return
     */
    public static boolean checkPassword(String password) {
        try {
            Pattern pattern = Pattern.compile("^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,20})$");
            Matcher matcher = pattern.matcher(password);
            return matcher.matches();
        }
        catch (Exception e) {
            log.error("密码验证异常，password={}", password, e);
        }
        
        return false;
    }
}
